#include <errno.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <fcntl.h>  
#include "buffer.h"
#include "preforkserver.h"
#include "epolleventhandlerimpl.h"
#include "httpprocessor.cpp"

#define MAXBUF 1024

const int SHMKEY = 1234555;
const int SUBPROCNUMB = 1;

int gport = 8001;

int main(int argc, char* argv[])
{ 
	if (argc > 1)
		gport = atoi(argv[1]);

	struct sockaddr_in svraddr;
	listenfd = socket( AF_INET, SOCK_STREAM, 0 );
	SetNonBlock( listenfd );
	bzero( &svraddr, sizeof(sockaddr_in) );
	svraddr.sin_family = AF_INET;
	inet_aton( "127.0.0.1", &(svraddr.sin_addr) );
	svraddr.sin_port = htons( gport );
	assert ( 0 == bind( listenfd, (sockaddr *)&svraddr, sizeof(svraddr) ) );
	listen(listenfd,1024);

	char line[512];
	socklen_t clilen;
	int nfds,connfd,n,sockfd,epfd;
	struct epoll_event ev,events[20];
	struct sockaddr_in cliaddr;
	int timeout = 500;
	
	HttpProcessor processor;
	EpollManager epolleventmng(listenfd,1024,20);
	assert ( epolleventmng.Init() == 0 );
	EpollEventHandlerImpl epolleventhandler( &epolleventmng, (Processor *)&processor); 
	for (;;)
	{
		int nfds = epolleventmng.WaitEvents(timeout);
		for ( int i=0; i<nfds; ++i )
		{
			epolleventhandler.Handle( epolleventmng.GetEventByPos(i) );
		}
	}
	return 0;
}
